import React, { createContext, useContext, useState, ReactNode } from 'react';

type Faction = {
  id: string;
  name: string;
  color: string;
  advantages: string;
};

type Player = {
  id: string;
  name: string;
  faction: Faction;
  isCommander: boolean;
};

type Unit = {
  id: string;
  type: UnitType;
  attack: number;
  defense: number;
  health: number;
  owner: string;
};

type Effect = {
  type: string;
  duration: number;
};

type GamePhase = 'setup' | 'battle' | 'diplomacy' | 'ended';

type Resources = {
  grain: number;
  horses: number;
  gunpowder: number;
  dragonVein: number;
};

type GameState = {
  currentPlayer: Player;
  players: Player[];
  gamePhase: GamePhase;
  resources: Resources;
  units: Unit[];
  effects: Effect[];
  timestamp?: number;
};

const initialState: GameState = {
  currentPlayer: {
    id: '',
    name: '',
    faction: {
      id: '',
      name: '',
      color: '',
      advantages: ''
    },
    isCommander: false
  },
  players: [],
  gamePhase: 'setup',
  resources: {
    grain: 0,
    horses: 0,
    gunpowder: 0,
    dragonVein: 0
  },
  units: [],
  effects: []
};

const GameContext = createContext<{
  state: GameState;
  dispatch: React.Dispatch<Partial<GameState>>;
}>({
  state: initialState,
  dispatch: () => null
});

export const GameProvider = ({ children }: { children: ReactNode }) => {
  const [state, setState] = useState<GameState>(initialState);

  const dispatch = (newState: Partial<GameState>) => {
    setState(prev => ({ ...prev, ...newState }));
  };

  return (
    <GameContext.Provider value={{ state, dispatch }}>
      {children}
    </GameContext.Provider>
  );
};

export const useGame = () => useContext(GameContext);
